#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");

#define DEVICE_NAME "my_platform_device"

static int irq_num;
static struct platform_device *pdev;

//中断处理函数
static irqreturn_t my_irq_handler(int irq, void *dev_id)
{
    pr_info("Interrupt received on IRQ %d\n", irq);
    return IRQ_HANDLED;
}

static int my_platform_probe(struct platform_device *dev)
{
    int ret;

    pr_info("my_platform_probe called\n");

    //中断映射
    irq_num = platform_get_irq(dev, 0);
    if (irq_num < 0) {
        pr_err("Failed to get platform IRQ\n");
        return irq_num;
    }

    //中断注册
    ret = devm_request_irq(&dev->dev, irq_num, my_irq_handler, IRQF_SHARED, DEVICE_NAME, dev);
    if (ret < 0) {
        pr_err("Failed to request IRQ %d\n", irq_num);
        return ret;
    }

    pr_info("Successfully registered IRQ %d\n", irq_num);

    return 0;
}

static int my_platform_remove(struct platform_device *dev)
{
    pr_info("my_platform_remove called\n");

    return 0;
}

static struct platform_driver my_platform_driver = {
    .probe = my_platform_probe,
    .remove = my_platform_remove,
    .driver = {
        .name = DEVICE_NAME,
        .owner = THIS_MODULE,
    },
};

static int __init my_platform_init(void)
{
    int ret;

    pdev = platform_device_alloc(DEVICE_NAME, -1);
    if (!pdev) {
        pr_err("Failed to allocate platform device\n");
        return -ENOMEM;
    }

    ret = platform_device_add(pdev);
    if (ret < 0) {
        pr_err("Failed to add platform device\n");
        platform_device_put(pdev);
        return ret;
    }

    ret = platform_driver_register(&my_platform_driver);
    if (ret < 0) {
        pr_err("Failed to register platform driver\n");
        platform_device_unregister(pdev);
        return ret;
    }

    pr_info("my_platform driver loaded\n");

    return 0;
}

static void __exit my_platform_exit(void)
{
    platform_driver_unregister(&my_platform_driver);
    platform_device_unregister(pdev);
    pr_info("my_platform driver unloaded\n");
}

module_init(my_platform_init);
module_exit(my_platform_exit);
